
import { useEffect,useState } from 'react';
import { v4 as uuidv4 } from 'uuid';
import { Divider, Popconfirm,Table, Input, Button, Space, Modal, Form, Select, DatePicker, message } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import {getVipRankApi ,addVipRankApi,updateVipRankApi,delVipRankApi,searchVipRankApi} from '../../../../api/vip/vip'
import useStore from '@/store';
const { Search } = Input;

const tailFormItemLayout = {
    wrapperCol: {
      xs: {
        span: 24,
        offset: 0,
      },
      sm: {
        span: 16,
        offset: 16,
      },
    },
  };
export default function VipRank(){
    const userInfo = useStore<any>((state: any) => state.userInfo)
    const [pageNum, setPageNum] = useState<any>(1);
    const [pageSize, setPageSize] = useState<any>(5);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [total,setTotal] = useState(0)
    let [vipRank,setVipRank] = useState()
    const [modalTitle,setModalTitle] =useState()
    const [form] = Form.useForm();
    useEffect(()=>{
        getVipRank(pageNum,pageSize)
    },[])
    let getVipRank = async (pageNum:any,pageSize:any)=>{
        let params = {
            pageNum:pageNum,
            pageSize:pageSize,
            belongToShop:userInfo.storeId
        }
        try {
           let vipRanRes = await getVipRankApi(params)
           if(vipRanRes.code ==200){
            setTotal(vipRanRes.total)
            let newVipRank = vipRanRes.vipRankList.map((vipRank:any)=>{
                return {
                    id:vipRank.id,
                    key:vipRank.id,
                    rankName:vipRank.rankName,
                    rank:vipRank.rank,
                    discount:vipRank.discount
                }
            })
            setVipRank(newVipRank)
           }
        } catch (error) {
            message.error('获取失败'+error)
        }
    }
    const showModal = (val:any,record:any) => {
        if(record){
            form.setFieldsValue(record)
        }else{
            form.setFieldsValue({id:uuidv4(),belongToShop:userInfo.storeId})
        }
        
        setModalTitle(val)
        setIsModalOpen(true);
      };
    
      const handleOk = () => {
        form.resetFields()
        setIsModalOpen(false);
        
      };
    
      const handleCancel = () => {
        form.resetFields()
        setIsModalOpen(false);
      };
      const onFinish =async (values: any) => {
        let params = {
            id:values.id,
            rankName:values.rankName,
            rank:values.rank,
            discount:values.discount,
            belongToShop:userInfo.storeId
        }
        if(modalTitle == '添加会员级别'){
           try {
            let addRankRes = await addVipRankApi(params)
            if(addRankRes.code == 200){
                message.success(addRankRes.msg)
                handleOk()
                getVipRank(pageNum,pageSize)
            }
           } catch (error) {
            handleOk()
            message.error('添加失败'+error)
           }
        }else{
            try {
                let updateRankRes = await updateVipRankApi(params)
                if(updateRankRes.code == 200){
                    message.success(updateRankRes.msg)
                    handleOk()
                    getVipRank(pageNum,pageSize)
                }
               } catch (error) {
                handleOk()
                message.error('修改失败'+error)
               }
        }
      };
      // 气泡删除确认框
  const confirm = async (e: any) => {
    let delStaffParams = {id:e.id}
     try {
      let delStaffRes = await delVipRankApi(delStaffParams)                  
      if(delStaffRes.code == 200){
        message.success('删除会员等级成功');
        getVipRank(pageNum,pageSize)
      }else{
        message.error('删除会员等级失败' + delStaffRes.msg);
      }
     } catch (error) {
      message.error('删除会员失败' + error);
     }
  };
  
  const cancel = (value:any) => {
    message.success('取消成功');
  };
  const onSearch = async(value: string) => {
    if(value){
    let searchParams = {keyWord:value,belongToShop:userInfo.storeId}
    try {
      let searchRes = await searchVipRankApi(searchParams)
      console.log(searchRes);
      
      if(searchRes.code ==200){
        let newRanklist = searchRes.ranklist.map((vipRank:any)=>{
          return {
            id:vipRank.id,
                    key:vipRank.id,
                    rankName:vipRank.rankName,
                    rank:vipRank.rank,
                    discount:vipRank.discount
          }
        })
        setVipRank(newRanklist)
        message.success(searchRes.msg)
      }else {
        message.error(searchRes.msg)
      }
    } catch (error) {
      message.error('搜索失败'+error)
    }
    }
  }
  const fresh = () => {
    try {
        getVipRank(pageNum,pageSize)
        message.success('刷新成功')
    } catch (error) {
        message.error('刷新成功')
    }
  };
  const pageNumChange: any = (page:any) => {
    setPageNum(page);
    getVipRank(page,pageSize)
  };
  
    const columns: ColumnsType<any> = [
        {
          title: 'ID',
          width: 100,
          dataIndex: 'id',
          key: '1',
          fixed: 'left',
        },
        {
          title: '会员称号',
          width: 100,
          dataIndex: 'rankName',
          key: '2',
          fixed: 'left',
          sorter: true,
        },
        {
            title: '会员权重',
            width: 100,
            dataIndex: 'rank',
            key: '3',
            fixed: 'left',
            sorter: true,
          },
          {
            title: '打折力度',
            width: 100,
            dataIndex: 'discount',
            key: '4',
            fixed: 'left',
            sorter: true,
          },
       
        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          width: 70,
          render: (record) => <div>
          <Button type="primary" style={{marginRight:'10px'}}
           onClick={()=>showModal('修改会员级别',record)}
            >修改</Button>
          
          <Popconfirm
            title="删除员工"
            description="删除后无法恢复!确认永久删除?"
            onConfirm={()=>confirm(record)}
            onCancel={()=>cancel(record)}
            okText="Yes"
            cancelText="No"
          >
            <Button type='primary'  danger>删除</Button>
          </Popconfirm>
        </div>,
        },
      ];
      
    return (
        <div>
             <div>
                <Search
                    placeholder="会员名字"
                    allowClear
                    enterButton="搜索"
                    // style={{ width: 304 }}
                    onSearch={onSearch}
                    style={{ width: 300 }}
                />
                <Button onClick={()=>showModal('添加会员级别',null)} style={{marginLeft:'20px'}}  type="primary" >
                    添加
                </Button>
                <Button style={{marginLeft:'20px'}}  onClick={fresh} type="primary" shape="circle" icon={<ReloadOutlined />} />
            </div>
            <div style={{marginTop:'20px'}}>
            <Table columns={columns} dataSource={vipRank}  pagination={{
                    pageSize: pageSize,
                    defaultCurrent: pageNum,
                    total: total,
                    onChange: pageNumChange,
                  }}  />;
            </div>
            <Modal footer={null} title={modalTitle} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
            <Form
                form={form}
                name="register"
                onFinish={onFinish}
                initialValues={{ residence: ['zhejiang', 'hangzhou', 'xihu'], prefix: '86' }}
                style={{ maxWidth: 600 }}
                scrollToFirstError
               
                >
                
                <Form.Item
                    name="id"
                    label="编号"
                    tooltip="不可操作"
                    rules={[{ required: true, message: 'id是必传参数', whitespace: true }]}
                >
                    <Input disabled={true} />
                </Form.Item>
                <Form.Item
                    name="rankName"
                    label="名称"
                    rules={[{ required: true, message: '名称是必传参数', whitespace: true }]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    name="discount"
                    label="打折力度"
                    rules={[{ required: true, message: '打折力度是必传参数', whitespace: true }]}
                >
                    <Input />
                </Form.Item>
                、

                
                <Form.Item {...tailFormItemLayout}>
                    <Button style={{marginRight:'20px'}}>
                    取消
                    </Button>
                    <Button type="primary" htmlType="submit">
                    {modalTitle == '添加会员级别' ? '添加': '修改'}
                    </Button>
                </Form.Item>
                </Form>
            </Modal>
        </div>
    )
}